package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.bean.ShoppingCart;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RequestMapping("/shoppingCart")
@RestController
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    //添加菜品或套餐到购物车
    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart){
        log.info("shoppingCart:{}",shoppingCart);
        //1.获取当前登录用户的id
        Long userId = BaseContext.get();

        //作业：
        //优化1：不使用name判断存在   1.先判断当前添加到购物车是菜品还是套餐   2.根据id判断当前菜品或套餐是否存在
        //优化2：判断当前的是否是菜品  如果是菜品 判断口味是否相同 口味相同：在原来的基础上number加1  口味不相同：添加一条新的记录

        //2.判断当前菜品或套餐是否已经添加到数据库了  根据name判断
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        //查询当前用户下的购物车数据
        wrapper.eq(ShoppingCart::getUserId,shoppingCart.getUserId());
        //查询某个菜品或套餐是否存在
        wrapper.eq(ShoppingCart::getName,shoppingCart.getName());
        ShoppingCart one = shoppingCartService.getOne(wrapper);

        //3.存在：number+1  不存在：设置number为1
        if(one!=null){
            one.setNumber(one.getNumber()+1);
        }else{
            one = shoppingCart;
            one.setNumber(1);
        }
        //4.补全字段：设置购物车记录的用户id、设置当前系统时间
        one.setUserId(userId);
        one.setCreateTime(LocalDateTime.now());

        //5.插入菜品或套餐记录到数据库
        shoppingCartService.saveOrUpdate(one);

        return R.success("添加购物车成功！");
    }

    //显示当前登录用户购物车中商品列表信息

    @GetMapping("/list")
    public R list(){
        //1.获取当前登录用户的id
        Long userId = BaseContext.get();
        //2.设置查询条件
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId!=null,ShoppingCart::getUserId,userId);
        //3.根据用户id查询其购物车数据列表
        List<ShoppingCart> list = shoppingCartService.list(wrapper);
        //4.返回数据
        return R.success(list);
    }

    @DeleteMapping("/clean")
    public R clean(){
        //1.获取当前登录用户的id
        Long userId = BaseContext.get();
        //2.设置删除条件
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId!=null,ShoppingCart::getUserId,userId);
        //3.根据用户id删除其购物车数据列表
        shoppingCartService.remove(wrapper);
        //4.返回数据
        return R.success("购物车清空成功！");
    }
}
